#![cfg_attr(debug_assertions, allow(dead_code, unused_imports, unused_variables, unused_mut))]
use function_name::named;
use macro_colors::*;
pub mod ftp_rar;
use crate::ftp_rar::{download_latest_sdk, expand_tilde, extract_sdk};
use log::{error, info, warn};
use my_commons::*;
use my_proc_macro::*;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;

/// Handles the SDK update process, including timestamp checks, downloading, cleaning, extracting, and timestamp updates.
pub fn update_sdk_rar() -> Result<(), String> {
    //================= Download the latest SDK
    let (sdk_file_name, sdk_data) = download_latest_sdk().map_err(|e| format!("SDK download failed: {}", e))?;

    //================= Save the SDK data to a temporary file
    let sdk_rar: PathBuf;
    let write_sdk_to_disk = true;
    let download_dir = r"~/Downloads";
    //------------------------
    if write_sdk_to_disk {
        let path_dir = expand_tilde(&PathBuf::from(download_dir));
        let temp_rar = path_dir.join(&sdk_file_name);
        println!("{}", format!("Saving SDK to local file: {}", temp_rar.display()).blue());
        // overwrite the content
        std::fs::write(&temp_rar, &sdk_data).map_err(|e| format!("Failed to save SDK to local file: {}", e))?;
        println!("{}", "SDK saved to local file successfully.".green());
        sdk_rar = temp_rar;
    } else {
        let temp_rar = tempfile::NamedTempFile::new().map_err(|e| format!("Failed to create temporary file: {}", e))?;
        std::fs::write(&temp_rar, sdk_data).map_err(|e| format!("Failed to write to temporary file: {}", e))?;
        sdk_rar = temp_rar.path().to_path_buf();
    }

    //================= Extract and apply the new SDK
    if let Err(e) = extract_sdk(&sdk_rar) {
        return Err(format!("SDK extraction failed: {}", e));
    } else {
        println!("{}", "SDK extracted successfully.".green());
    }

    //================= delete temporary file if not needed
    if !write_sdk_to_disk {
        std::fs::remove_file(&sdk_rar).map_err(|e| format!("Failed to delete temporary file: {}", e))?;
    }

    Ok(())
}

#[mydbginfo]
pub fn tt() -> Result<(), String> {
    return update_sdk_rar();
}
